/**
 * 
 */
package validator;

import java.awt.Color;
import java.awt.Component;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;

/**
 * @author nguyen.nhat.nguyen
 *
 */
public class JEmailValidator extends JLabel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 
	 */
	public JEmailValidator() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public boolean check()
	{
		Component obj = this.getLabelFor();
		boolean isValid = false;

		Pattern patt = Pattern.compile(ValidatorConst.EMAIL_PATTERN);
		Matcher matcher;

		if(obj instanceof JTextField)
		{
	        matcher = patt.matcher(((JTextField)obj).getText());
	        if(matcher.matches())
	        {
	        	isValid = true;
	        }
		}

		if(obj instanceof JTextPane)
		{
			matcher = patt.matcher(((JTextPane)obj).getText());
			if(matcher.matches())
	        {
	        	isValid = true;
	        }
		}

		if(obj instanceof JTextArea)
		{
			matcher = patt.matcher(((JTextArea)obj).getText());
			if(matcher.matches())
	        {
	        	isValid = true;
	        }
		}
		
		if(!isValid)
        {
        	this.setText(ValidatorConst.VALIDATOR_EMAIL_MESSAGE);
        	obj.setBackground(Color.GREEN);
        }
        this.setVisible(!isValid);

		return isValid;
	}
}
